﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using KC.DataAccess.MV;

public partial class rss : System.Web.UI.Page
{
	private string cs = System.Configuration.ConfigurationManager.ConnectionStrings["MV8"].ConnectionString;

	protected void Page_Load(object sender, EventArgs e)
	{
		MV8DataContext dc = new MV8DataContext(cs);
		Response.Clear();
		Response.ContentType = "application/rss+xml";

		XmlDocument xDoc = BuildRSS(ref dc);
		dc.Dispose();
		if (xDoc == null) return;

		Response.Write(xDoc.OuterXml);
		Response.Flush();
		Response.End();
	}

	private XmlDocument BuildRSS(ref MV8DataContext dc)
	{
		XmlDocument xDoc = BuildHeader();
		var posts = (from p in dc.Posts
					 where p.isEnabled
					 orderby p.ID descending
					 select p).Take(25);

		XmlNode xe = xDoc.SelectSingleNode(@"rss/channel");
		foreach (Post post in posts)
			xe.AppendChild(BuildPostRssElement(ref dc, ref xDoc, post));

		return xDoc;
	}

	private XmlDocument BuildHeader()
	{
		XmlDocument xDoc = new XmlDocument();
		XmlElement root = xDoc.CreateElement("rss");
		root.Attributes.Append(xDoc.CreateAttribute("version"));
		root.Attributes["version"].InnerText = "2.0";

		XmlElement
			channel = xDoc.CreateElement("channel"),
			title = xDoc.CreateElement("title"),
			link = xDoc.CreateElement("link"),
			description = xDoc.CreateElement("description");

		title.InnerText = "Kevin Connolly's blog";
		description.InnerText = "The blog of a Senior .NET Developer and independent contractor in Colorado Springs";
		link.InnerText = "http://blogs.code-slinger.com/rss.aspx";

		channel.AppendChild(title);
		channel.AppendChild(link);
		channel.AppendChild(description);
		root.AppendChild(channel);
		xDoc.AppendChild(root);
		return xDoc;
	}
	private XmlElement BuildPostRssElement(ref MV8DataContext dc, ref XmlDocument xDoc, Post post)
	{
		XmlElement
			item = xDoc.CreateElement("item"),
			title = xDoc.CreateElement("title"),
			description = xDoc.CreateElement("description"),
			link = xDoc.CreateElement("link"),
			pubdate = xDoc.CreateElement("pubDate");
		title.InnerText = post.Title;
		description.InnerText = string.IsNullOrEmpty(post.Description) ? post.Body.Length > 1000 ? post.Body.Substring(0, 1000) : post.Body : post.Description;
		link.InnerText = "http://www.kconnolly.net/Post.aspx?Title=" + post.FriendlyName;
		pubdate.InnerText = string.Format("{0:R}", post.Created);

		item.AppendChild(title);
		item.AppendChild(description);
		item.AppendChild(link);
		item.AppendChild(pubdate);
		return item;
	}
}